package be.android.forap.dataprovider;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import be.android.forap.Constants;
import be.android.forap.R;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ForapAdapter extends BaseAdapter {

	private Activity activity;
	private RowData[] data;
	private RowData[] forapdata;
	private boolean mOnlyShowForapData;
	private Context mContext;
	private static LayoutInflater inflater=null;

	public ForapAdapter(Activity a,Context context, boolean showAllOtherContacts, boolean showForapContacts) {
		activity = a;
		mContext = context;
		forapdata=extractForapRowData(getForApContacts());
		if(showAllOtherContacts && showForapContacts){
			data= extractRowData(getContacts());
		}
		if(!showAllOtherContacts && showForapContacts){
			data = forapdata;       	
		}
		if(showAllOtherContacts && !showForapContacts){
			data = removeForapRows(extractRowData(getContacts()));       	
		}
		if(!showAllOtherContacts && !showForapContacts){
			data = new RowData[1]; 
			data[0] = new RowData(0, "");
		}
		inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	private RowData[] removeForapRows(RowData[] allContacts) {
		ArrayList<RowData> result = new ArrayList<RowData>();

		List<Long> forap_id_list = getContactIdArray(forapdata);
		for(int i=0;i<allContacts.length;i++){
			if(!forap_id_list.contains(allContacts[i].getContactId())){
				result.add(allContacts[i]);
			}
		}
		return result.toArray(new RowData[result.size()]);
	}

	/**
	 * Obtains the contact list for the currently selected account.
	 *
	 * @return A cursor for for accessing the contact list.
	 */
	private Cursor getContacts(){
		// Run query
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		String[] projection = new String[] {
				ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME
		};
		String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" +
				"1" + "'";
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

		ContentResolver resolver = mContext.getContentResolver();
		return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
	}


	/**
	 * Obtains the contact list for the currently selected account.
	 *
	 * @return A cursor for for accessing the contact list.
	 */
	private Cursor getForApContacts(){
		// Run query
		Uri uri = ContactsContract.RawContacts.CONTENT_URI;
		String[] projection = new String[] {
				ContactsContract.RawContacts.CONTACT_ID,
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.RawContacts.SOURCE_ID
		};
		String selection = 
				RawContacts.DELETED + "=0 AND " +
						ContactsContract.RawContacts.ACCOUNT_TYPE + " = '" +
						Constants.ACCOUNT_TYPE + "'";
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

		ContentResolver resolver = mContext.getContentResolver();

		return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
	}

	private static RowData[] extractRowData(Cursor c){
		RowData[] dataList = new RowData[c.getCount()];
		int index_contact_id = c.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
		int index_display_name = c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
		for(int i=0;i<c.getCount();i++){
			c.moveToPosition(i);
			dataList[i] = new RowData(c.getLong(index_contact_id), c.getString(index_display_name));
		}
		c.close();
		return dataList;
	}

	private static RowData[] extractForapRowData(Cursor c){
		RowData[] forapList = new RowData[c.getCount()];
		int index_contact_id = c.getColumnIndexOrThrow(ContactsContract.RawContacts.CONTACT_ID);
		int index_display_name = c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
		int index_contact_forapid = c.getColumnIndexOrThrow(ContactsContract.RawContacts.SOURCE_ID);
		for(int i=0;i<c.getCount();i++){
			c.moveToPosition(i);
			forapList[i]=new RowData(c.getLong(index_contact_id), c.getString(index_display_name)
					,c.getString(index_contact_forapid));
		}
		c.close();
		return forapList;
	}

	public int getCount() {
		return data.length;
	}

	public String getItem(int position) {
		return data[position].getDisplayName();
	}

	public long getItemId(int position) {
		return -1;
	}

	public String getForapGlobalId(int position) {
		RowData rd = getRow(position);
		return rd.getForapId();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View vi=convertView;
		if(convertView==null)
			vi = inflater.inflate(R.layout.contactslist_item, null);

		TextView text=(TextView)vi.findViewById(R.id.clist_textview_contactLabel);;
		ImageView image=(ImageView)vi.findViewById(R.id.clist_image_key);

		List<Long> forap_id_list = getContactIdArray(forapdata);
		text.setText(data[position].getDisplayName());
		// List list = Arrays.asList(forapdata.getIds());
		if(forap_id_list.contains(data[position].getContactId())) {
			//imageLoader.DisplayImage(data[position], image);
			// ;
			image.setImageResource(R.drawable.kgpg_key2_kopete);
		}else{
			// text.setText(forapdata.getDisplayName(position));
			image.setImageResource(R.drawable.ic_no_key);//android.R.drawable.editbox_dropdown_dark_frame);
		}
		return vi;
	}

	public RowData getRow(int position){
		if(isForapRow(position)){
			List<Long> forap_contactid_list = getContactIdArray(forapdata);
			for(int i=0;i<forap_contactid_list.size();i++){
				if(forapdata[i].getContactId() == data[position].getContactId()){
					return forapdata[i];
				}
			}
		}else{
			return data[position];
		}

		return null;
	}

	public boolean isForapRow(int position){
		if(mOnlyShowForapData)
			return true;
		List<Long> forap_contactid_list = getContactIdArray(forapdata);
		return (forap_contactid_list.contains(data[position].getContactId()));    	
	}

	private List<Long> getContactIdArray(RowData[] rd){
		long[] ids = new long[rd.length];
		for(int i=0;i<rd.length;i++){
			ids[i] = rd[i].getContactId();
		}
		return longAsList(ids);		
	}

	public static List<Long> longAsList(final long[] l) {
		return new AbstractList<Long>() {
			public Long get(int i) {
				return l[i];
			}
			// throws NPE if val == null
			public Long set(int i, Long val) {
				Long oldVal = l[i];
				l[i] = val;
				return oldVal;
			}
			public int size() { return l.length;}
		};
	}

	private String[] getDisplayNames(RowData[] rd){
		String[] names = new String[rd.length];
		for(int i=0;i<rd.length;i++){
			names[i] = rd[i].getDisplayName();
		}
		return names;
	}

	public String[] getDisplayNames(){
		return getDisplayNames(data);
	}

	public long getContactId(int position) {
		return data[position].getContactId();
	}
	
	private String personalDisplayName = "Own Public Key";

	public void addPersonalRow(){
		RowData rd= new RowData(-1, personalDisplayName);
		ArrayList<RowData> all = new ArrayList<RowData>();
		all.add(rd);
		Collections.addAll(all,data);
		data = all.toArray(new RowData[all.size()]);
	}

	public boolean isPersonalRow(int pos) {
		return (data[pos].getContactId() == -1 && data[pos].getDisplayName().equals(personalDisplayName));
	}
	
	/******
	 * Search id
	 */
	public long searchContactId(String displayname){
		for(int i=0;i<forapdata.length;i++){
			if(forapdata[i].getDisplayName().equals(displayname)){
				return forapdata[i].getContactId();
			}
		}
		return -1;
	}
	
	
//	private ArrayList<Map<String, String>> getExtraInfo(){
//		ArrayList<Map<String, String>> mPeopleList = new ArrayList<Map<String, String>>();
//		List<Long> id_list = getContactIdArray(data);
//
//		ContentResolver resolver = mContext.getContentResolver();
//
//		Cursor people = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//
//		while (people.moveToNext()){
//			String contactName = people.getString(people.getColumnIndex(
//					ContactsContract.Contacts.DISPLAY_NAME));
//
//			String contactId = people.getString(people.getColumnIndex(
//					ContactsContract.Contacts._ID) );
//			String hasPhone = people.getString(people.getColumnIndex(
//					ContactsContract.Contacts.HAS_PHONE_NUMBER));
//			/*String hasPhone = people.getString(people.getColumnIndex(
//					ContactsContract.Contacts.HAS_PHONE_NUMBER));
//			/*String hasEmai = people.getString(people.getColumnIndex(
//					ContactsContract.CommonDataKinds.Email.HAS_PHONE_NUMBER));
//			/*if(id_list.contains(contactId))
//				Log.d("EXTRA",contactId + " = "+id_list.get(1) );*/
//			if (((Integer.parseInt(hasPhone) > 0) && id_list.contains(Long.parseLong(contactId))) ){
//				Log.d("EXTRA pASSED",contactId + contactName);
//				// You know have the number so now query it like this
//				Cursor phones = resolver.query(
//						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
//						null,
//						ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
//						null, null);
//				while (phones.moveToNext()) {
//
//					//store numbers and display a dialog letting the user select which.
//					String phoneNumber = phones.getString(
//							phones.getColumnIndex(
//									ContactsContract.CommonDataKinds.Phone.NUMBER));
//
//					String numberType = phones.getString(phones.getColumnIndex(
//							ContactsContract.CommonDataKinds.Phone.TYPE));
//
//					Map<String, String> NamePhoneType = new HashMap<String, String>();
//
//					NamePhoneType.put("Name", contactName);
//					NamePhoneType.put("Phone", phoneNumber);
//					if(TextUtils.isEmpty(numberType)){
//						NamePhoneType.put("Type", "Not defined");
//					}
//					else {
//						if(numberType.equals("0"))
//							NamePhoneType.put("Type", "Work");
//						else
//							if(numberType.equals("1"))
//								NamePhoneType.put("Type", "Home");
//							else if(numberType.equals("2"))
//								NamePhoneType.put("Type",  "Mobile");
//							else
//								NamePhoneType.put("Type", "Other");
//					}
//
//					//Then add this map to the list.
//					Log.d("add",contactName + phoneNumber);
//					mPeopleList.add(NamePhoneType);
//				}
//				phones.close();
//			}
//		}
//		people.close();
//
//		Log.d("length",""+mPeopleList.size());
//		//resolver.query(people);
//		return mPeopleList;
//	}

	
}